//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Host;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Utilities;
using System.Web.UI;
namespace DotNetNuke.Framework
{
	public class jQuery
	{
		private const string jQueryDebugFile = "~/Resources/Shared/Scripts/jquery/jquery.js";
		private const string jQueryMinFile = "~/Resources/Shared/Scripts/jquery/jquery.min.js";
		private const string jQueryVersionKey = "jQueryVersionKey";
		private const string jQueryVersionMatch = "(?<=jquery:\\s\")(.*)(?=\")";
		public const string DefaultHostedUrl = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
		private static bool GetSettingAsBoolean(string key, bool defaultValue)
		{
			bool retValue = defaultValue;
			try {
				object setting = HttpContext.Current.Items[key];
				if (setting != null) {
					retValue = Convert.ToBoolean(setting);
				}
			} catch (Exception ex) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}
			return retValue;
		}
		private static bool IsScriptRegistered()
		{
			return HttpContext.Current.Items["jquery_registered"] != null;
		}
		public static bool IsInstalled {
			get {
				string minFile = JQueryFileMapPath(true);
				string dbgFile = JQueryFileMapPath(false);
				return File.Exists(minFile) || File.Exists(dbgFile);
			}
		}
		public static bool IsRequested {
			get { return GetSettingAsBoolean("jQueryRequested", false); }
		}
		public static bool UseDebugScript {
			get { return Host.jQueryDebug; }
		}
		public static bool UseHostedScript {
			get { return Host.jQueryHosted; }
		}
		public static string HostedUrl {
			get { return Host.jQueryUrl; }
		}
		public static string Version {
			get {
				string ver = Convert.ToString(DataCache.GetCache(jQueryVersionKey));
				if (string.IsNullOrEmpty(ver)) {
					if (IsInstalled) {
						string jqueryFileName = JQueryFileMapPath(false);
						string jfiletext = File.ReadAllText(jqueryFileName);
						Match verMatch = Regex.Match(jfiletext, jQueryVersionMatch);
						if (verMatch != null) {
							ver = verMatch.Value;
							DataCache.SetCache(jQueryVersionKey, ver, new System.Web.Caching.CacheDependency(jqueryFileName));
						} else {
							ver = Localization.GetString("jQuery.UnknownVersion.Text");
						}
					} else {
						ver = Localization.GetString("jQuery.NotInstalled.Text");
					}
				}
				return ver;
			}
		}
		public static string JQueryFileMapPath(bool GetMinFile)
		{
			return HttpContext.Current.Server.MapPath(JQueryFile(GetMinFile));
		}
		public static string JQueryFile(bool GetMinFile)
		{
			string jfile = jQueryDebugFile;
			if (GetMinFile) {
				jfile = jQueryMinFile;
			}
			return DotNetNuke.Common.Globals.ResolveUrl(jfile);
		}
		public static string GetJQueryScriptReference()
		{
			string scriptsrc = HostedUrl;
			if (!UseHostedScript) {
				scriptsrc = JQueryFile(!UseDebugScript);
			}
			return string.Format(DotNetNuke.Common.Globals.glbScriptFormat, scriptsrc);
		}
		public static void RegisterScript(System.Web.UI.Page page)
		{
			RegisterScript(page, jQuery.GetJQueryScriptReference());
		}
		public static void RegisterScript(System.Web.UI.Page page, string script)
		{
			if (!IsScriptRegistered()) {
				HttpContext.Current.Items["jquery_registered"] = true;
				Literal headscript = new Literal();
				headscript.Text = script;
				Control objCSS = page.Header.FindControl("SCRIPTS");
                objCSS.Controls.AddAt(0, headscript);
			}
		}
		public static void RequestRegistration()
		{
			HttpContext.Current.Items["jQueryRequested"] = true;
		}
		[Obsolete("Deprectaed in DNN 5.1. Replaced by IsRequested.")]
		public static bool IsRquested {
			get { return IsRequested; }
		}
	}
}
